package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClientSelf;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

@Slf4j
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ShopMapper shopMapper;

    /**
     * 基于StringRedisTemplate封装一个缓存工具类，满足下列需求：
     *
     * * 方法1：将任意Java对象序列化为json并存储在string类型的key中，并且可以设置TTL过期时间
     * * 方法2：将任意Java对象序列化为json并存储在string类型的key中，并且可以设置逻辑过期时间，用于处理缓
     *
     * 存击穿问题
     *
     * * 方法3：根据指定的key查询缓存，并反序列化为指定类型，利用缓存空值的方式解决缓存穿透问题
     * * 方法4：根据指定的key查询缓存，并反序列化为指定类型，需要利用逻辑过期解决缓存击穿问题
     */

    @Resource
    private CacheClientSelf cacheClientSelf;

    @Override
    public Result queryById(Long id) {
        //该方法可以解决缓存穿透，缓存雪崩，缓存击穿的问题
        Shop shop = cacheClientSelf.queryWithLogicalExpire(CACHE_SHOP_KEY + id, id, Shop.class, this::getById);
        if(shop == null){
            return Result.fail("商铺不存在");
        }else{
            return Result.ok(shop);
        }

    }

    /**
     *  解决缓存穿透问题，缓存null的方法
     * @param id
     * @return
     */
    public Shop queryToCachePenetration(Long id){
        //1.根据商铺的id查询redis中是否有商铺
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        if(StringUtil.isNotBlank(shopJson)){
            //2.如果商品命中，先把字符串转换为对象，然后直接返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //要增加判断，如果为空值，那么直接返回
        if(shopJson != null){
            return null;
        }
        //3.如果商铺未命中，查询数据库
        Shop shopInfo = getById(id);
        if(shopInfo == null){
            /*return Result.fail("店铺不存在");*/
            //为了解决缓存穿透的问题，这里要返回空值给缓存
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        /*        log.info(shopInfo.toString());*/
        String s = JSONUtil.toJsonStr(shopInfo);
        /*    log.info(s);*/
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shopInfo),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shopInfo;
    }

    /**
     *  使用互斥锁解决缓存击穿
     * @param id
     * @return
     */
    public Shop queryToResolveCache(Long id){
        //1.根据商铺的id查询redis中是否有商铺
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        if(StringUtil.isNotBlank(shopJson)){
            //2.如果商品命中，先把字符串转换为对象，然后直接返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //要增加判断，如果为空值，那么直接返回
        if(shopJson != null){
            return null;
        }

        try {
            //3.如果商铺未命中，尝试获取互斥锁
            boolean mutex = getMutex(id);
            if(mutex){
                //还要在判断一次是否缓存中没有数据
                shopJson = stringRedisTemplate.opsForValue().get(key);
                if(shopJson != null){
                    ReleaseMutex(id);
                    return JSONUtil.toBean(shopJson, Shop.class);
                }
                //获取锁成功
                //查询数据库中的数据
                Shop shopInfo = getById(id);
                if(shopInfo == null){
                    /*return Result.fail("店铺不存在");*/
                    //为了解决缓存穿透的问题，这里要返回空值给缓存
                    stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
                    return null;
            }
                stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shopInfo),CACHE_SHOP_TTL, TimeUnit.MINUTES);
                return shopInfo;

            }else {
                //获取锁失败
                Thread.sleep(50);
                return queryToResolveCache(id);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            //4.释放互斥锁
            ReleaseMutex(id);

        }
    }

    /**
     * 创建线程池
     */
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * 设置缓存过期时间解决缓存击穿问题
     * @param id
     * @return
     */
    public Shop queryWithLogicalExpire(Long id) {
        //1.根据商铺的id查询redis中是否有商铺
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        if(StringUtil.isBlank(shopJson)){
            //2.1未命中
            return null;
        }
        //2.2 命中判断缓存是否过期
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        if(expireTime.isAfter(LocalDateTime.now())) {
            // 2.3.未过期，直接返回店铺信息
            return shop;
        }
        //2.4.已过期，尝试获取互斥锁
        /*String lockKey = LOCK_SHOP_KEY + id;*/
        boolean mutex = getMutex(id);
        if(mutex){
            //3.1.获取锁成功,再次判断缓存中的数据是否过期
            if(expireTime.isAfter(LocalDateTime.now())) {
                // 未过期，直接返回店铺信息
                return shop;
            }
            CACHE_REBUILD_EXECUTOR.submit(()-> {
                //3.2开启独立的线程，缓存重建
                try {
                    saveShop2Redis(id, 10L);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }finally {
                    ReleaseMutex(id);
                }

            });

        }
            return shop;
        }



    public void saveShop2Redis(Long id,Long time) throws InterruptedException {
        RedisData redisData = new RedisData();
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        //查询数据库
        Shop shop = getById(id);
        Thread.sleep(50);
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(time));
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(redisData));
    }



    /**
     * 获取互斥锁
     * @param id
     * @return 成功则返回true
     */
    private  boolean getMutex(Long id){
        String key = LOCK_SHOP_KEY + id;
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 释放互斥锁
     * @param id
     */
    private void ReleaseMutex(Long id){
        String key = LOCK_SHOP_KEY + id;
        stringRedisTemplate.delete(key);

    }

    @Transactional  //保持数据库和redis缓存的原子性
    @Override
    public Result updateShop(Shop shop) {
        //先去判断是否存在该店铺
        Long id = shop.getId();
        if(id == null){
            return Result.fail("店铺不存在，无法进行修改");
        }
        //更新数据库
        updateById(shop);
        //删除缓存
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + id);
        return Result.ok();
    }




}
